package components.listen
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.getQualifiedClassName;

	internal class Border
	{
		private var _dis:DisplayObject;
		private var _color:uint = 0x0099ff;
		private var _obj:Object;
		
		private var _container:Sprite;
		
		private var _mcTxt:Sprite;
		private var _txt:TextField;
		
		public function Border( obj:Object )
		{
			_obj = obj;
			_dis = _obj as DisplayObject;
			if( _dis != null ) init();
		}
		
		private function init():void
		{
			_container = new Sprite();
			_container.mouseChildren = false;
			_container.mouseEnabled = false;
			
			_mcTxt = new Sprite();
			_container.addChild( _mcTxt );
			
			_txt = new TextField();
			_txt.defaultTextFormat = new TextFormat(null, 10, 0xfffff);
			_txt.text = getQualifiedClassName(_obj);
			_txt.width = _txt.textWidth + 4;
			_txt.height = _txt.textHeight + 4;
			_txt.border = false;
			
			_mcTxt.graphics.beginFill( _color );
			_mcTxt.graphics.drawRect( 0, 0, _txt.width, _txt.height );
			_mcTxt.graphics.endFill();
			_mcTxt.addChild( _txt );
			
			_dis.addEventListener( Event.REMOVED_FROM_STAGE, onRemoveFromStage );
			
			DemonDebugger.stage.addEventListener( Event.RENDER, onRender );
			DemonDebugger.stage.addEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
		
		private function refresh():void
		{
			if( _container.parent==null ) DemonDebugger.stage.addChild( _container );
			var rect:Rectangle = _dis.getBounds( DemonDebugger.stage );
			_container.x = rect.x>>0;
			_container.y = rect.y>>0;
			_container.graphics.clear();
			_container.graphics.lineStyle( 2, _color );
			_container.graphics.drawRect( 0, 0, rect.width, rect.height );
			_container.graphics.endFill();
			
			_mcTxt.x = 0;
			_mcTxt.y = -_mcTxt.height;
		}
		
		private function onRemoveFromStage( e:Event ):void
		{
			if( _container.parent ) _container.parent.removeChild( _container );
		}
		
		private function onEnterFrame( e:Event ):void
		{
			if( _dis.stage ) DemonDebugger.stage.invalidate();
		}
		
		private function onRender( e:Event ):void
		{
			if( _dis.stage ) refresh();
		}
	}
}